package StudyCode.summary.regularexpressionsmatch;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class RegularExpressionAppendOrReplace {
	public static void main(String[] argv) {
		String input = "Thanks, thanks very much";
		System.out.println("替换前：" + input);
		System.out.println("替换后：");
		String regex = "([Tt])hanks";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(input);
		StringBuffer sb = new StringBuffer();
		while (matcher.find()) {
			if (matcher.group(1).equals("T")) {
				matcher.appendReplacement(sb, "Thank you");
			} else {
				matcher.appendReplacement(sb, "thank you");
			}
		}
		matcher.appendTail(sb);
		System.out.println(sb.toString());
		sb.setLength(0);
		matcher.reset();
		String replacement = "$1hank you";
		while (matcher.find()) {
			matcher.appendReplacement(sb, replacement);
		}
		matcher.appendTail(sb);
		System.out.println(sb.toString());
		System.out.println(matcher.replaceAll(replacement));
		System.out.println(input.replaceAll(regex, replacement));

	}
}
